package com.ytjj.qmyx.mall.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.qmyx.mall.mapper.ExpressOrdersMapper;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.AppMessageItemResponse;
import com.ytjj.qmyx.mall.model.dto.AppMessageNoReadResponse;
import com.ytjj.qmyx.mall.model.dto.ExpressResRecordDto;
import com.ytjj.qmyx.mall.model.vo.ImMessageInfoVO;
import com.ytjj.qmyx.mall.service.ImMessageInfoService;
import com.ytjj.qmyx.mall.service.MessageRecordService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.users.mapper.UsersBalanceRecordMapper;
import com.ytjj.qmyx.users.model.UsersBalanceRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/message")
@Slf4j
@RefreshScope
public class AppMessageController extends BaseController {
    @Autowired
    private MessageRecordService messageRecordService;
    @Autowired
    private OrdersService ordersService;
    @Resource
    private UsersBalanceRecordMapper usersBalanceRecordMapper;
    @Resource
    private ImMessageInfoService imMessageInfoService;
    @Resource
    private ExpressOrdersMapper expressOrdersMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    /**
     * 未读消息数
     * @return
     */
    @GetMapping("/messageNoReadNum")
    public CommonResult messageNoReadNum() {
        AppMessageNoReadResponse response = new AppMessageNoReadResponse();
        try {
            UsersResponse usersResponse = getCurrentUser();
            String tel = usersResponse.getTel();

            MessageRecordDto list_type_one = messageRecordService.getMessageListNoReadNum(tel, 1, null);
            MessageRecordDto list_type_two = messageRecordService.getMessageListNoReadNum(tel, 3, null);
            MessageRecordDto list_type_three = messageRecordService.getMessageListNoReadNum(tel, 4, null);

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            response.setOrderNum(null == list_type_one ? 0 : list_type_one.getNum());
            if (null != list_type_one && null != list_type_one.getCreateTime()) {
                response.setOrderTime(sdf.format(list_type_one.getCreateTime()));
            }
            if (null != list_type_one && null != list_type_one.getPushId()) {
                if (list_type_one.getPushId().equals(1)) {
                    response.setOrderContent("您有1个待付款订单商品即将售馨，快去支付吧>>");
                }else {
                    response.setOrderContent("您的订单已经打包完毕，准备装车，点击查看详情>>");
                }
            }
            response.setExpressNum(null == list_type_two ? 0 : list_type_two.getNum());
            if (null != list_type_two && null != list_type_two.getCreateTime()) {
                response.setExpressTime(sdf.format(list_type_two.getCreateTime()));
            }
            if (null != list_type_two && null != list_type_two.getPushId()) {
                response.setExpressContent("您有1件商品已签收，点击查看>>");
            }
            response.setWalletNum(null == list_type_three ? 0 : list_type_three.getNum());
            if (null != list_type_three && null != list_type_three.getCreateTime()) {
                response.setWalletTime(sdf.format(list_type_three.getCreateTime()));
            }
            UsersBalanceRecord usersBalanceRecord = usersBalanceRecordMapper.newestAddRecordByUserId(usersResponse.getId());
            if (null != list_type_three && null != list_type_three.getPushId()) {
                response.setWalletContent("您有一笔金额到账，到账余额" + (null == usersBalanceRecord ? "0" : usersBalanceRecord.getBalance()) + "元，快去看看吧>>");
            }
            if (!StringUtils.isEmpty(tel)) {
                ImMessageInfoVO imMessageInfoVO = imMessageInfoService.queryUsersNewestMessage(tel);
                if (null != imMessageInfoVO) {
                    response.setImNum(imMessageInfoVO.getNum());
                    response.setImContent(imMessageInfoVO.getContent());
                    response.setImTime(null == imMessageInfoVO.getCreateTime() ? null : sdf.format(imMessageInfoVO.getCreateTime()));
                }
            }
            response.setAllNum(response.getOrderNum() + response.getExpressNum() + response.getWalletNum() + response.getImNum());
            return CommonResult.success(response);
        } catch (Exception e) {
            log.error("===获取消息列表未读数异常==={}", e);
        }
        return CommonResult.success(response);
    }

    /**
     * 获取系统通知历史记录
     * @param type 1-订单 2-物流 3-钱包
     * @return
     */
    @GetMapping("/historyList")
    public CommonResult historyList(Integer type) {
        try {
            log.info("===message historyList===type:{}", type);
            UsersResponse usersResponse = getCurrentUser();
            String tel = usersResponse.getTel();
            log.info("===message historyList===tel:{}", tel);
            List<MessageRecord> list = messageRecordService.getMessageItem(tel, type);
            try {
                messageRecordService.updateMessageReadStatus(tel, type);
            } catch (Exception e) {
                log.error("===更新系统通知消息已读未读异常==={},{}", tel, type);
                log.error("==={}", e);
            }
            if (CollectionUtils.isEmpty(list)) {
                return CommonResult.success(new ArrayList<>());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm:ss");

            List<MessageItemRecordDto> resultList = new ArrayList<>();
            list.stream().forEach(item -> {
                if (StringUtils.isEmpty(item.getBizNo())) {
                    return;
                }
                Orders orders = ordersService.getByOrderNo(item.getBizNo());
                if (null == orders && !type.equals(3)) {
                    return;
                }
                OrdersInfo ordersInfo = null;
                ExpressOrders newestExpressOrders = null;//最新的物流记录
                String newestExpressInfo = "";
                if (type.equals(3)) {
                    ordersInfo = ordersService.getOrdersInfoByExpressNo(item.getBizNo());

                    ExpressOrdersExample expressOrdersExample = new ExpressOrdersExample();
                    expressOrdersExample.createCriteria().andNoEqualTo(item.getBizNo());
                    expressOrdersExample.setOrderByClause("create_time desc");
                    List<ExpressOrders> expressOrdersListResult =  expressOrdersMapper.selectByExample(expressOrdersExample);
                    if (!CollectionUtils.isEmpty(expressOrdersListResult)) {
                        newestExpressOrders = expressOrdersListResult.get(0);
                        if (StringUtils.isNotEmpty(newestExpressOrders.getInfoText())) {
                            List<ExpressResRecordDto> resRecordDtos = (List<ExpressResRecordDto>) JSONObject.parse(newestExpressOrders.getInfoText());
                            if (!CollectionUtils.isEmpty(resRecordDtos)) {
                                resRecordDtos = resRecordDtos.stream().sorted(Comparator.comparing(ExpressResRecordDto::getFtime)).collect(Collectors.toList());
                                newestExpressInfo = resRecordDtos.get(0).getContext();
                            }
                        }
                    }
                }else {
//                    ordersInfo = ordersService.getOrdersInfoById(orders.getId());
                    OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
                    ordersInfoExample.createCriteria().andOrderIdEqualTo(orders.getId());
                    List<OrdersInfo> ordersInfoList = ordersInfoMapper.selectByExample(ordersInfoExample);
                    if (CollectionUtils.isEmpty(ordersInfoList)) {
                        return;
                    }
                    ordersInfo = ordersInfoList.get(0);
                }
                if (null == ordersInfo) {
                    return;
                }
                MessageItemRecordDto dto = new MessageItemRecordDto();
                dto.setCreateTime(sdf.format(item.getCreateTime()));
                dto.setOrderId(orders.getId());
                dto.setOrderInfoId(ordersInfo.getId());
                dto.setOrderNo(item.getBizNo());
                switch (item.getPushId()) {
                    case 1 :
                        dto.setTitle("您的订单即将失效");
                        dto.setRemark("您有1个待付款订单商品[" + ordersInfo.getProductName() + "]即将售馨，快去支付吧>>");
                        break;
                    case 2:
                        dto.setTitle("您的订单已完成");
                        dto.setRemark("订单[" + ordersInfo.getProductName() + "]已经从完成，点击查看详情>>");
                        break;
                    case 3:
                        dto.setProductName(ordersInfo.getProductName());
                        dto.setProductImg(ordersInfo.getProductImg());
                        dto.setExpressInfo(newestExpressInfo);//最新的物流地点
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
                resultList.add(dto);
            });
            AppMessageItemResponse response = new AppMessageItemResponse();
            response.setItem(resultList);
            return CommonResult.success(response);
        } catch (Exception e) {
            log.error("===获取消息列表未读数异常==={}", e);
        }
        return CommonResult.success(new AppMessageItemResponse());
    }

}
